<template>
  <div>
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
      <template #footer>
        <a-space :size="20">
          <a-button type="outline" @clikc="router.go(-1)">
            <template #default>取消</template>
          </a-button>
          <a-button type="primary" @click="submit">
            <template #default>执行</template>
          </a-button>
        </a-space>
      </template>
      <div style="margin-bottom: 150px">
        <div class="info-item">
          <TitleBox
            title="基本消息"
            style="width: 95%; margin-bottom: 35px"
          ></TitleBox>
          <div
            style="
              width: 100%;
              display: flex;
              justify-content: center;
              padding: 20px;
            "
            ><a-form
              style="width: 60%"
              ref="formRef"
              :model="form"
              auto-label-width
            >
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="销售出库单号:"
                    ><a-input
                      style="width: 320px"
                      placeholder="系统自动生成"
                      disabled
                      v-model="form.number"
                  /></a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item
                    required
                    field="orderId"
                    label="关联销售订单号："
                  >
                    <a-select
                      v-model="form.orderId"
                      :disabled="route.query.id"
                      :style="{ width: '320px' }"
                      @change="getInfo"
                    >
                      <a-option
                        v-for="item in OrderList"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.number }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="出库单下达时间："
                    ><a-date-picker
                      placeholder="系统自动生成"
                      :style="{ width: '320px' }"
                      disabled
                  /></a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item label="客户名称："
                    ><a-input
                      :style="{ width: '320px' }"
                      v-model="form.clientCompanyName"
                      disabled
                      allow-clear
                  /></a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="业务员：">
                    <a-input
                      :style="{ width: '320px' }"
                      v-model="form.userStaffName"
                      disabled
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item label="收货人：">
                    <a-input
                      :style="{ width: '320px' }"
                      v-model="form.consigneeName"
                      disabled
                      placeholder="暂无"
                      allow-clear
                    />
                    <a-button type="text" v-if="shiftIn" @click="setConsignee"
                      >切换收货人</a-button
                    >
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="收货人联系电话：">
                    <a-input
                      :style="{ width: '320px' }"
                      v-model="form.consigneePhone"
                      disabled
                      placeholder="暂无"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item label="送货地址：">
                    <a-input
                      v-model="form.consigneeAddress"
                      disabled
                      :style="{ width: '320px' }"
                      placeholder="暂无"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="计划出货时间：">
                    <a-date-picker
                      v-model="form.outboundDate"
                      :style="{ width: '320px' }"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="24">
                  <a-form-item label="备注：">
                    <a-textarea v-model="form.remark" allow-clear />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- <div style="width: 100%; display: flex; margin: 20px 50px">
            <a-space>
              <div
                style="
                  width: 4px;
                  height: 15px;
                  background-color: rgba(61, 126, 255, 1);
                  border: none;
                  border-radius: 2px;
                "
              >
              </div>
              <a-space :size="50"
                ><h3>物料出库明细 ：</h3
                ><div
                  ></a-space
              >
            </a-space>
          </div> --><TitleBox
            style="width: 95%; margin-bottom: 35px"
            title="产品出库明细"
            ><template #buts
              ><a-button
                type="primary"
                v-show="!route.query.id"
                @click="getSelectDetail"
                >新增</a-button
              ></template
            ></TitleBox
          >
          <div
            style="
              width: 90%;
              margin-left: 5%;
              box-shadow: 1px 1px 5px rgb(153 153 153 / 35%);
              border-radius: 4px;
            "
          >
            <div style="padding: 30px">
              <div style="text-align: right" class="button-item"></div>
              <a-table
                :data="form.OutboundWarehouseItem"
                :scroll="scroll"
                :pagination="false"
                row-key="id"
                :row-selection="rowSelection"
                v-model:selectedKeys="selectedKeys"
                @select="onSelect"
                v-bind="args"
              >
                <template #columns>
                  <a-table-column :width="80" align="center">
                    <template #title> 序号 </template>
                    <template #cell="{ rowIndex }">
                      <div style="position: relative">
                        <div>{{ rowIndex + 1 }}</div>
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column
                    align="center"
                    :width="80"
                    title="物料编码"
                    data-index="number"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    :width="80"
                    title="物料名称"
                    data-index="name"
                  >
                  </a-table-column>

                  <a-table-column
                    align="center"
                    :width="80"
                    title="规格型号"
                    data-index="spec"
                  >
                  </a-table-column>

                  <a-table-column
                    align="center"
                    :width="80"
                    title="订单数量"
                    data-index="amount"
                  >
                  </a-table-column>
                  <!-- <a-table-column
                align="center"
                :width="80"
                title="已来料数量"
                data-index="amounts"
              >
              </a-table-column> -->
                  <a-table-column
                    align="center"
                    :width="80"
                    title="未交货数量"
                    data-index="canOutboundAmount"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    :width="80"
                    title="库存总量"
                    data-index="totalStock"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    :width="80"
                    title="当前空闲库存量"
                    data-index="freeStock"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    :width="80"
                    title="安全库存量"
                    data-index="safetyStock"
                  >
                  </a-table-column>
                  <!-- <a-table-column
                    align="center"
                    :width="80"
                    title="检测类别"
                    data-index="detectionType"
                  >
                    <template #cell="{ record }">
                      <a-select v-model="record.detectionType">
                        <a-option :value="1">抽检</a-option>
                        <a-option :value="2">全检</a-option>
                        <a-option :value="3">免检</a-option>
                      </a-select>
                    </template>
                  </a-table-column> -->
                  <a-table-column
                    align="center"
                    :width="80"
                    title="已占用库存量"
                    data-index="occupiedAmount"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    :width="80"
                    title="本次出库数量"
                    data-index="itemAmount"
                  >
                    <template #cell="{ record }">
                      <a-input-number
                        :min="1"
                        :max="record.amount"
                        @change="setItemAmount(record)"
                        v-model="record.itemAmount"
                      />
                    </template>
                  </a-table-column>
                </template> </a-table
            ></div>
          </div>
        </div>
      </div>
    </pageHeader>
  </div>

  <SelectDetail
    v-model:visible="modelVisible"
    :detailData="detailData"
    v-if="modelVisible"
    @selectDetailEmit="selectDetailEmit"
  ></SelectDetail>
  <checkOccupiedVue
    v-model:visible="OccupiedVisible"
    v-if="OccupiedVisible"
    :OccupiedId="OccupiedId"
  />
  <consigneeTable
    v-model:visible="ConsigneeVisible"
    v-if="ConsigneeVisible"
    :id="form.clientCompanyId"
    @selectConsignee="selectConsignee"
  ></consigneeTable>
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    computed,
    onMounted,
    defineAsyncComponent,
  } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import {
    GetClientOrder,
    GetClientOrderDetail,
    putPoductOccupied,
    GetOrderDetail,
  } from '@/api/order-management/client-order/index';
  import { GetClientDetailTabs } from '@/api/order-management/client-management/client-list/index';
  import {
    GetPersonnelinformation,
    Getsingleperson,
  } from '@/api/home/System settings/personal-information/index';
  import { PostOutboundAll } from '@/api/inventory-management/outbound-management/sales-shipment-outbound/sales-outbound/index';
  import { cloneDeep } from 'lodash';
  import { Message } from '@arco-design/web-vue';
  import { useOrderStore } from '@/store';
  import checkOccupiedVue from './checkOccupied/index.vue';
  import consigneeTable from './consigneeTable/index.vue';
  //   import SelectDetail from './select-detail/index.vue';

  let SelectDetail = defineAsyncComponent(
    () => import('./select-detail/index.vue')
  );
  const formRef = ref();
  const OrderStore = useOrderStore();
  const OccupiedVisible = ref(false);
  const ConsigneeVisible = ref(false);
  const OccupiedId = ref();
  const detailData = ref();
  const orderNumber = ref();
  // 获取人员信息
  const Personne = ref();
  const Personnelinformation = async () => {
    const res = await GetPersonnelinformation({ page: 0, size: -1 });
    Personne.value = res.content.data;
  };
  Personnelinformation();
  const modelVisible = ref(false);
  const route = useRoute();
  const router = useRouter();
  const tableRef = ref();
  const modelVisibleQr = ref(false);
  const title: string = '新建销售出库单';
  const breadCrumb: string[] = [
    '库存管理',
    '出库管理',
    '销售出库',
    '新建销售出库单',
  ];
  const entryType = Number(route.query.entryType);
  const form = ref<any>({
    number: '',
    orderId: undefined,
    outboundType: 1,
    warehouseStaffId: undefined,
    inspectionStaffId: undefined,
    consigneeName: '',
    consigneePhone: '',
    consigneeAddress: '',
    outboundDate: '',
    remark: '',
    state: 1,
    OutboundWarehouseItem: [],
    salesOrderNumber: undefined,
    clientCompanyName: '',
    clientCompanyId: undefined,
    userStaffName: '',
    userStaffId: undefined,
  });
  const shiftIn = ref(false);
  // 表格配置
  const args = reactive({
    stripe: false,
    scroll: {
      y: 2000,
      x: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'id', // 批量选择按钮 以合同名称来作为key
  });

  const getProduct = async () => {
    try {
      if (route.query.id) {
        const res = await GetClientOrderDetail({ id: Number(route.query.id) });
        const {
          number,
          clientCompanyName,
          clientCompanyId,
          userStaffName,
          userStaffId,
          id,
        } = res;
        // if (res.person.length) {
        //   let data: any = res.person.filter((i: any) => i.primaryContact === 1);
        //   if (!data.length) data = res;
        //   form.value.consigneeName = data[0].name;
        //   form.value.consigneePhone = data[0].phone;
        //   form.value.consigneeAddress = data[0].address;
        // }
        // if (res.person.length > 1) shiftIn.value = true;
        form.value.salesOrderNumber = number;
        form.value.clientCompanyName = clientCompanyName;
        form.value.clientCompanyId = clientCompanyId;
        form.value.userStaffName = userStaffName;
        form.value.userStaffId = userStaffId;

        form.value.orderId = id;
        form.value.OutboundWarehouseItem = OrderStore.getOutboundData.map(
          (item: any) => {
            item = JSON.parse(
              JSON.stringify(item).replace('id', 'orderProductId')
            );
            return item;
          }
        );
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  getProduct();

  const OrderList = ref();
  const getOrderList = async () => {
    const res = await GetClientOrder({ page: 1, size: -1 });
    OrderList.value = res.content.filter(
      (ele: any) => ele.state === 2 || ele.state === 3
    );
  };
  getOrderList();
  const isSelectSupplier = ref(false);

  const getInfo = async (ids: number) => {
    form.value.OutboundWarehouseItem = [];
    const res = await GetOrderDetail({ id: ids });
    const msg = await GetClientDetailTabs({
      id: res.clientCompanyId,
      typeId: 10,
    });
    if (msg) {
      let consigneeData = msg.filter((i: any) => i.primaryContact === 1);
      if (!consigneeData.length) consigneeData = [{ ...msg[0] }];
      if (msg.length > 1) shiftIn.value = true;
      form.value.consigneeName = consigneeData[0].name;
      form.value.consigneePhone = consigneeData[0].phone;
      form.value.consigneeAddress = consigneeData[0].address;
    } else {
      shiftIn.value = false;
    }
    const {
      number,
      clientCompanyName,
      clientCompanyId,
      userStaffName,
      userStaffId,
      id,
    } = res;

    form.value.salesOrderNumber = number;
    form.value.clientCompanyName = clientCompanyName;
    form.value.clientCompanyId = clientCompanyId;
    form.value.userStaffName = userStaffName;
    form.value.userStaffId = userStaffId;

    form.value.orderId = id;
    detailData.value = res.orderProduct;
  };

  const getUserInfo = async (id: any) => {
    const res = await Getsingleperson({ id });
    form.value.StaffPhone = res.mobile;
  };

  const submit = () => {
    formRef.value.validate(async (res) => {
      if (!res) {
        form.value.outboundDate = new Date(form.value.outboundDate).toJSON();
        await PostOutboundAll({
          ...form.value,
        });
        form.value.OutboundWarehouseItem.forEach((item) => {
          if (item.totalStock < item.safetyStock || !item.totalStock) {
            Message.warning(
              `${item.name}产品的总库存量已低至安全库存量，请及时补充`
            );
          }
        });
        router.back();
      }
    });
  };

  const getSelectDetail = () => {
    if (!form.value.orderId && !form.value.purchaseOrderNumber) {
      Message.error('请选择关联销售订单');
      return;
    }
    modelVisible.value = true;
  };

  const selectDetailEmit = (val?: any) => {
    detailData.value.forEach((item: any) => {
      const res = val.some((Element: any) => Element.name === item.name);
      if (res) {
        item = JSON.parse(JSON.stringify(item).replace('id', 'orderProductId'));
        item.state = 1;
        form.value.OutboundWarehouseItem.push(item);
      }
    });
  };

  const checkOccupied = (id?: number) => {
    OccupiedVisible.value = true;
    OccupiedId.value = id;
  };

  const setConsignee = () => {
    ConsigneeVisible.value = true;
  };

  const selectConsignee = (val: any) => {
    const { name, phone, remark, address } = val;
    form.value.consigneeName = name;
    form.value.consigneePhone = phone;
    form.value.consigneeAddress = address;
  };

  // const setItemAmount = (val: any) => {
  //   if (val.itemAmount > val.occupiedAmount && val.itemAmount > val.freeStock) {
  //     Message.error('本次出库数量不达标。');
  //     val.itemAmount = 0;
  //   }
  // };
</script>

<style scoped lang="less">
  .basic-item {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid rgba(242, 243, 245, 0.852);
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }

  .info-item {
    width: 100%;
  }

  .report-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
  }

  .order-info {
    width: 95%;
    margin: 20px auto;
  }

  :deep(.arco-form) {
    width: 100%;
  }

  // .box {
  //   position: absolute;
  //   bottom: 0;
  //   left: 0;
  //   padding-top: 10px;
  //   margin-top: 20px;
  //   border-top: 1px solid #e4e4e4;
  //   display: flex;
  //   justify-content: end;
  //   width: 100%;
  // }
</style>
